<template>
  <div class="pending-approvals-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="工作流名称">
            <el-input
              v-model="searchForm.workflowName"
              placeholder="请输入工作流名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="申请人">
            <el-input
              v-model="searchForm.creator"
              placeholder="请输入申请人"
              clearable
              style="width: 150px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="紧急程度">
            <el-select
              v-model="searchForm.priority"
              placeholder="请选择紧急程度"
              clearable
              style="width: 120px"
            >
              <el-option label="全部" :value="undefined" />
              <el-option label="紧急" :value=1 />
              <el-option label="普通" :value=0 />
              <el-option label="低" :value=-1 />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="RefreshRight">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 待审批列表 -->
    <div class="approvals-list-container">
      <el-card>
        <template #header>
          <div class="card-header">
            <span class="card-title">待我审批</span>
            <span class="approvals-count">共 {{ total }} 条待审批</span>
          </div>
        </template>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 审批表格 -->
        <div v-else-if="approvalsList.length > 0">
          <el-table
            :data="approvalsList"
            stripe
            style="width: 100%"
            @row-click="handleRowClick"
          >
            <el-table-column prop="workflowName" label="工作流名称" min-width="150">
              <template #default="{ row }">
                <div class="workflow-name-cell">
                  <el-icon class="workflow-icon" color="#409eff">
                    <Document />
                  </el-icon>
                  <span class="workflow-name">{{ row.workflowName }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="creator" label="申请人" width="100">
              <template #default="{ row }">
                <span class="creator-name">{{ row.creator }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="currentNode" label="当前节点" width="120">
              <template #default="{ row }">
                <span class="current-node">{{ row.currentNodeName || '-' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="priority" label="紧急程度" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityType(row.priority)" size="small">
                  {{ getPriorityLabel(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="createdAt" label="申请时间" width="160">
              <template #default="{ row }">
                <span class="created-time">{{ formatDate(row.createTime) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="waitingDays" label="等待天数" width="100">
              <template #default="{ row }">
                <span class="waiting-days" :class="getWaitingDaysClass(row.waitingDays)">
                  {{ getWaitingDays(row.createTime) }} 天
                </span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button
                    size="small"
                    type="primary"
                    text
                    @click.stop="handleViewDetail(row)"
                  >
                    查看详情
                  </el-button>
                  
                  <el-button
                    size="small"
                    type="success"
                    text
                    @click.stop="handleApprove(row)"
                  >
                    通过
                  </el-button>
                  
                  <el-button
                    size="small"
                    type="danger"
                    text
                    @click.stop="handleReject(row)"
                  >
                    拒绝
                  </el-button>
                  
                  <el-button
                    size="small"
                    type="info"
                    text
                    @click.stop="handleTransfer(row)"
                  >
                    转办
                  </el-button>
                  
                  <el-button
                    size="small"
                    type="warning"
                    text
                    @click.stop="handleComment(row)"
                  >
                    评论
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无待审批事项">
            <el-button type="primary" @click="handleRefresh">
              刷新列表
            </el-button>
          </el-empty>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 审批详情弹窗 -->
    <ApplicationDetailDialog
      v-model:visible="detailDialogVisible"
      :application="selectedApplication"
      source="pendingApprovals"
      :show-approval-actions="true"
      @approve="handleApproveFromDialog"
      @reject="handleRejectFromDialog"
    />

    <!-- 审批操作弹窗 -->
    <el-dialog
      v-model="approvalDialogVisible"
      :title="approvalAction === 'approve' ? '审批通过' : '审批拒绝'"
      width="500px"
      @close="resetApprovalDialog"
    >
      <el-form :model="approvalForm" label-width="80px">
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            :rows="4"
            :placeholder="approvalAction === 'approve' ? '请输入审批意见（可选）' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approvalDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="approvalLoading"
            @click="confirmApproval"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 转办弹窗 -->
    <el-dialog
      v-model="transferDialogVisible"
      title="转办申请"
      width="500px"
      @close="resetTransferDialog"
    >
      <el-form :model="transferForm" label-width="80px">
        <el-form-item label="转办给" required>
          <div class="transfer-users-display">
            <div v-if="transferForm.nodeUserList.length > 0" class="selected-users">
              <el-tag
                v-for="(user, index) in transferForm.nodeUserList"
                :key="index"
                closable
                @close="removeTransferUser(index)"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ user.name }}
              </el-tag>
            </div>
            <el-button
              type="primary"
              plain
              @click="openTransferUserSelector"
              style="margin-top: 8px;"
            >
              {{ transferForm.nodeUserList.length > 0 ? '重新选择' : '选择转办人' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="转办原因">
          <el-input
            v-model="transferForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入转办原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="transferLoading"
            @click="confirmTransfer"
          >
            确定转办
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评论弹窗 -->
    <el-dialog
      v-model="commentDialogVisible"
      title="添加评论"
      width="500px"
      @close="resetCommentDialog"
    >
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="工单名称">
          <span class="workflow-name-display">{{ selectedApplication?.workflowName }}</span>
        </el-form-item>
        <el-form-item label="评论内容" required>
          <el-input
            v-model="commentForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commentDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="commentLoading"
            @click="confirmComment"
          >
            添加评论
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 转办人员选择弹窗 -->
    <TransferUserSelector
      v-model:visible="transferEmployeesDialogVisible"
      :data="transferForm.nodeUserList"
      @change="handleTransferUsersChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search,
  RefreshRight,
  Document
} from '@element-plus/icons-vue'
import ApplicationDetailDialog from './components/ApplicationDetailDialog.vue'
import { getPendingApprovals, approveWorkflow, rejectWorkflow, transferWorkflow, addComment } from '/@/api/workflow'
import type { WorkflowInstance } from './types'
import TransferUserSelector from './components/TransferUserSelector.vue'

// 响应式数据
const loading = ref(false)
const approvalsList = ref<WorkflowInstance[]>([])
const total = ref(0)
const detailDialogVisible = ref(false)
const selectedApplication = ref<WorkflowInstance | null>(null)
const approvalDialogVisible = ref(false)
const approvalLoading = ref(false)
const approvalAction = ref<'approve' | 'reject'>('approve')
const transferDialogVisible = ref(false)
const transferLoading = ref(false)
const commentDialogVisible = ref(false)
const commentLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  workflowName: '',
  creator: '',
  priority: undefined
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20
})

// 审批表单
const approvalForm = reactive({
  comment: ''
})

// 转办表单
const transferForm = reactive({
  nodeUserList: [] as Array<{type: number, targetId: number, name: string}>,
  reason: ''
})

// 转办弹窗相关
const transferEmployeesDialogVisible = ref(false)

// 评论表单
const commentForm = reactive({
  comment: ''
})

// 方法
const fetchApprovalsList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      workflowName: searchForm.workflowName,
      creator: searchForm.creator,
      priority: searchForm.priority
    }
    
    const response = await getPendingApprovals(params)
    approvalsList.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('获取待审批列表失败')
    console.error('获取待审批列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchApprovalsList()
}

const handleReset = () => {
  searchForm.workflowName = ''
  searchForm.creator = ''
  searchForm.priority = undefined
  pagination.page = 1
  fetchApprovalsList()
}

const handleRefresh = () => {
  fetchApprovalsList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchApprovalsList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchApprovalsList()
}

const handleRowClick = (row: WorkflowInstance) => {
  handleViewDetail(row)
}

const handleViewDetail = (application: WorkflowInstance) => {
  selectedApplication.value = application
  detailDialogVisible.value = true
}

const handleApprove = (application: WorkflowInstance) => {
  selectedApplication.value = application
  approvalAction.value = 'approve'
  approvalDialogVisible.value = true
}

const handleReject = (application: WorkflowInstance) => {
  selectedApplication.value = application
  approvalAction.value = 'reject'
  approvalDialogVisible.value = true
}

const handleTransfer = (application: WorkflowInstance) => {
  selectedApplication.value = application
  transferDialogVisible.value = true
}

const handleComment = (application: WorkflowInstance) => {
  selectedApplication.value = application
  commentDialogVisible.value = true
}

const handleApproveFromDialog = (application: WorkflowInstance) => {
  handleApprove(application)
}

const handleRejectFromDialog = (application: WorkflowInstance) => {
  handleReject(application)
}

const confirmApproval = async () => {
  if (!selectedApplication.value) return
  
  approvalLoading.value = true
  try {
    const params = {
      approveType: approvalAction.value === 'approve' ? 1 : 2,
      nodeId: selectedApplication.value.currentNodeId,
      comment: approvalForm.comment
    }
    
    if (approvalAction.value === 'approve') {
      await approveWorkflow(params)
      ElMessage.success('审批通过成功')
    } else {
      if (!approvalForm.comment.trim()) {
        ElMessage.warning('请输入拒绝原因')
        return
      }
      await rejectWorkflow(params)
      ElMessage.success('审批拒绝成功')
    }
    
    approvalDialogVisible.value = false
    resetApprovalDialog()
    fetchApprovalsList()
  } catch (error) {
    ElMessage.error('审批操作失败')
    console.error('审批操作失败:', error)
  } finally {
    approvalLoading.value = false
  }
}

const confirmTransfer = async () => {
  if (!selectedApplication.value || transferForm.nodeUserList.length === 0) {
    ElMessage.warning('请选择转办人')
    return
  }
  
  transferLoading.value = true
  try {
    const params = {
      workflowInstanceId: selectedApplication.value.id,
      nodeUserList: transferForm.nodeUserList,
      reason: transferForm.reason
    }
    
    await transferWorkflow(params)
    ElMessage.success('转办成功')
    transferDialogVisible.value = false
    resetTransferDialog()
    fetchApprovalsList()
  } catch (error) {
    ElMessage.error('转办失败')
    console.error('转办失败:', error)
  } finally {
    transferLoading.value = false
  }
}

const resetApprovalDialog = () => {
  approvalForm.comment = ''
  selectedApplication.value = null
}

const resetTransferDialog = () => {
  transferForm.nodeUserList = []
  transferForm.reason = ''
  selectedApplication.value = null
}

// 打开转办人员选择器
const openTransferUserSelector = () => {
  transferEmployeesDialogVisible.value = true
}

// 处理转办人员选择变化
const handleTransferUsersChange = (selectedUsers: Array<{type: number, targetId: number, name: string}>) => {
  transferForm.nodeUserList = selectedUsers
  transferEmployeesDialogVisible.value = false
}

// 移除转办人员
const removeTransferUser = (index: number) => {
  transferForm.nodeUserList.splice(index, 1)
}

const confirmComment = async () => {
  if (!selectedApplication.value || !commentForm.comment.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  commentLoading.value = true
  try {
    const params = {
      nodeId: selectedApplication.value.currentNodeId,
      comment: commentForm.comment
    }
    
    await addComment(params)
    ElMessage.success('评论添加成功')
    commentDialogVisible.value = false
    resetCommentDialog()
    fetchApprovalsList()
  } catch (error) {
    ElMessage.error('评论添加失败')
    console.error('评论添加失败:', error)
  } finally {
    commentLoading.value = false
  }
}

const resetCommentDialog = () => {
  commentForm.comment = ''
  selectedApplication.value = null
}



const getPriorityType = (priority: number | string) => {
  const typeMap: Record<number | string, string> = {
    1: 'danger',
    0: '',
    '-1': 'info',
    // 兼容旧的字符串格式
    'urgent': 'danger',
    'normal': '',
    'low': 'info'
  }
  return typeMap[priority] || ''
}

const getPriorityLabel = (priority: number | string) => {
  const labelMap: Record<number | string, string> = {
    1: '紧急',
    0: '普通',
    '-1': '低',
    // 兼容旧的字符串格式
    'urgent': '紧急',
    'normal': '普通',
    'low': '低'
  }
  return labelMap[priority] || '普通'
}

const getWaitingDays = (createTime: string) => {
  if (!createTime) return 0
  const now = new Date()
  const created = new Date(createTime)
  const diffTime = Math.abs(now.getTime() - created.getTime())
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

const getWaitingDaysClass = (days: number) => {
  if (days >= 7) return 'urgent'
  if (days >= 3) return 'warning'
  return 'normal'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch {
    return '-'
  }
}

// 生命周期
onMounted(() => {
  fetchApprovalsList()
})
</script>

<style scoped>
.pending-approvals-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-container {
  margin-bottom: 20px;
}

.approvals-list-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.approvals-count {
  color: #909399;
  font-size: 14px;
}

.loading-container {
  padding: 20px;
}

.workflow-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workflow-icon {
  flex-shrink: 0;
}

.workflow-name {
  font-weight: 500;
  color: #303133;
}

.creator-name {
  color: #606266;
  font-weight: 500;
}

.current-node {
  color: #606266;
}

.created-time {
  color: #909399;
  font-size: 13px;
}

.waiting-days {
  font-weight: 500;
}

.waiting-days.normal {
  color: #67c23a;
}

.waiting-days.warning {
  color: #e6a23c;
}

.waiting-days.urgent {
  color: #f56c6c;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.empty-state {
  padding: 40px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.workflow-name-display {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}
.transfer-users-display {
  .selected-users {
    min-height: 32px;
    padding: 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #f5f7fa;
    margin-bottom: 8px;
  }
  
  .selected-users:empty {
    display: none;
  }
}
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .pending-approvals-container {
    padding: 12px;
  }

  .search-container :deep(.el-form) {
    flex-direction: column;
  }

  .search-container :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }

  .pagination-container {
    :deep(.el-pagination) {
      justify-content: center;
      flex-wrap: wrap;
    }
  }
}
</style>